<?php
/**
 * @author
 * 招聘流程
 */
apf_require_controller("Abstract");
apf_require_class('Bll_Flow_Lumesse');
class Flow_RecruitmentController extends AbstractController {

    //ceo 主管
    //hr hrd 主管
    //编制内 编制外
    private $error_item;
    public function handle_request() {
        $params = $this->request->get_parameters();
        $flow_id = intval($params['id']);

        $flow = $this->_get_bll_flow()->get_flow_by_id($flow_id);

        $allow_opt = array();//操作权限
        $recruit = array();
        $this->view = intval($params['view']);//已处理/未处理标记，
        $this->flow_stage= array();
        $operate_log = array();

        if($flow){
            if($flow['flow_type'] != Const_Flow::FLOW_TYPE_RECRUIT){
                $this->show_tips('ERROR_PARAM',"/flow/",Const_Tip::ERROR);
            }
            //验证查看权限,ceo没有配置多城市，所以不检测权限
            $ceo_uid = APF::get_instance()->get_config('ceo_uid');
            if($ceo_uid != $this->user_info['user_id']){
                if(!$this->_check_read_flow_auth($flow['work_city_id'],$flow['flow_type'],$flow['flow_stage']+1,$flow['flow_id'])){
                    $this->show_tips('ERROR_AUTH');
                }
            }
            //找出申请人的lumesse所有下属部门
            $this->lums_dep = Bll_Flow_Lumesse::get_instance()->get_user_luemsse_department($flow['user_id']);
            //同步lumesse出错问题
            if(isset($params['sync'])){
                $this->execute_input_error($flow);
            }
            $this->relations = $this->_get_bll_hroa()->get_user_relation(array($flow['user_id']));
            //操作日志
            $operate_log = $this->_get_operate_log($flow_id);
            //检测流程是否已经结束
            if($flow['now_status'] == Const_Flow::FLOW_STATUS_DOING){
                //当前操作阶段,操作权限
                $allow_opt = $this->_get_flow_stage($operate_log,$flow);
                //特殊跳步
            }
            //数据验证
            $check_post = true;
            if($this->request->is_post_method() ){
                $check_post = $this->_check_post_param($allow_opt,$params);
            }
            if($this->request->is_post_method() && $check_post){
                //如果无操作权限则跳出
                if(!$allow_opt){
                    $this->show_tips('ERROR_AUTH');
                }
                $error_msg = $this->_execute_recruit($allow_opt,$params,$flow);

                //如果全部无错误，则成功
                $nex_url = Flow_Urls::flow_list();
                if(!$error_msg){
                    $this->show_tips('OPT_SUCCESS',$nex_url,1);
                }else{
                    $this->show_tips('ERROR_APPLY_RECRUIT',$nex_url.$error_msg);
                }
            }else{

                $user = $this->_get_bll_hroa()->get_user_base_info($flow['user_id'],$get_job=true);

                $recruit = $this->_get_bll_flow_recruit()->get_recruit_by_id($flow_id);

                $recruit = $this->_build_recruit_info($recruit);
            }
            if(!$check_post){
                $recruit = $this->_build_post_error($recruit,$params);
            }
        }else{
            $this->show_tips('ERROR_PARAM',"/flow/",Const_Tip::ERROR);
        }
        //构造允许操作的input的name数组
        $allow_names = array();
        if($allow_opt){
            foreach($allow_opt as $opt_id){
                $temp = $this->_get_submit_names($opt_id);
                $allow_names = array_merge($allow_names,$temp);
            }
        }
        $plan_in = $this->_build_last_form_list($flow['user_id'],$flow['recruit']);

        $ceo_operate_hide = $this->_get_cxo_operate_hide($operate_log,$flow);

        $allow_opts = array_values($allow_opt);
        $this->request->set_attribute('allow_opts',$allow_opts);
        $this->request->set_attribute('flow',$flow);
        $this->request->set_attribute('ceo_operate_hide',$ceo_operate_hide);
        $this->request->set_attribute('allow_names',$allow_names);
        $this->request->set_attribute('error',$this->error_item);
        $this->request->set_attribute('user',$user);
        $this->request->set_attribute('operate_log',$operate_log);
        $this->request->set_attribute('all_flows',$this->_build_all_flows());
        $this->request->set_attribute('plan_in',array(Const_Flow::FLOW_RECRUIT_2, Const_Flow::FLOW_RECRUIT_3,Const_Flow::FLOW_RECRUIT_14));
        $this->request->set_attribute('recruit',$recruit);
        $this->request->set_attribute('lums_dep',$this->lums_dep);
        return "Flow_Recruitment";
    }
    /**
     * 页面中最后能操作的流程表单项
     * @param $recruit 编制内还是编制外
     */
    private function _build_last_form_list($user_id,$recruit){
        if($recruit){
            $ceo_uid = $this->apf->get_config('ceo_uid');
            $flow_list = $this->_build_all_flows();
            $stage_list = array_keys($flow_list);
            for($i=0;$i<count($this->relations[$user_id]);$i++){
                if($i>0 && $this->relations[$user_id][$i]==$ceo_uid){//如果审批的上一级是ceo，就不用批了
                    break;
                }
                $plan_in[] = $stage_list[$i];
            }
            $plan_in[] = Const_Flow::FLOW_RECRUIT_12;
            $plan_in[] = Const_Flow::FLOW_RECRUIT_13;
            $plan_in[] = Const_Flow::FLOW_RECRUIT_14;
        }else{
            $plan_in=array(Const_Flow::FLOW_RECRUIT_14);//编制内
            $ceo_uid = APF::get_instance()->get_config('ceo_uid');
            if($ceo_uid!=$this->user_info['user_id']){
                $plan_in =array_merge($plan_in,array(Const_Flow::FLOW_RECRUIT_2, Const_Flow::FLOW_RECRUIT_3));
            }
        }
        return $plan_in;
    }
    private function _build_all_flows(){
        $opt = Const_Flow::flow_to_opt();
        $recruit_opt = $opt[Const_Flow::FLOW_TYPE_RECRUIT];
        $pre_stage = "";
        $data = array(
                Const_Flow::FLOW_RECRUIT_2=>array('name'=>'first','title'=>'一级主管'),
                Const_Flow::FLOW_RECRUIT_3=>array('name'=>'second','title'=>'二级主管'),
                Const_Flow::FLOW_RECRUIT_4=>array('name'=>'third','title'=>'三级主管'),
                Const_Flow::FLOW_RECRUIT_5=>array('name'=>'four','title'=>'四级主管'),
                Const_Flow::FLOW_RECRUIT_6=>array('name'=>'five','title'=>'五级主管'),
                Const_Flow::FLOW_RECRUIT_7=>array('name'=>'six','title'=>'六级主管'),
                Const_Flow::FLOW_RECRUIT_8=>array('name'=>'seven','title'=>'七级主管'),
                Const_Flow::FLOW_RECRUIT_9=>array('name'=>'eight','title'=>'八级主管'),
                Const_Flow::FLOW_RECRUIT_10=>array('name'=>'nine','title'=>'九级主管'),
                Const_Flow::FLOW_RECRUIT_11=>array('name'=>'ten','title'=>'十级主管'),
                Const_Flow::FLOW_RECRUIT_12=>array('name'=>'hrd','title'=>'HRD'),
                Const_Flow::FLOW_RECRUIT_13=>array('name'=>'ceo','title'=>'CEO'),
                Const_Flow::FLOW_RECRUIT_14=>array('name'=>'hr','title'=>'招聘'),
        );
        foreach($recruit_opt as $stage => $opt){
            $data[$stage]['phase'] = max($opt);
            $data[$stage]['stage'] = $stage;
            $data[$stage]['pre_stage'] = $pre_stage;
            if($pre_stage){
                $data[$pre_stage]['next_stage'] = $stage;
            }
            $pre_stage = $stage;
        }
        unset($data[Const_Flow::FLOW_RECRUIT_1]);
        return $data;
    }
    /**
     * 处理提交错误
     */
    private function _build_post_error($recruit,$params){

        $all_flow = $this->_build_all_flows();
        foreach($all_flow as $flow){
            $key_reason = $flow['name'].'_reason';
            if(isset($params[$key_reason])){
                $recruit[$key_reason] = $params[$key_reason];
            }
        }
        if(isset($params['hr_lumesse'])){
            $recruit['hr_lumesse'] = $params['hr_lumesse'];
        }
        if(isset($params['"lums_dep_id"'])){
            $recruit['"lums_dep_id"'] = $params['"lums_dep_id"'];
        }
        return $recruit;
    }
    /**
     * 主管为ceo
     */
    private function _get_cxo_operate_hide($operate_log,$flow){
        $result = array();
        $cxo_uids = $this->_get_cxo_user_ids();
        foreach($operate_log as $log){
            if(in_array($log['opt_user_id'], $cxo_uids)){
                $result = $this->_get_cxo_operate_next_leader($log['flow_stage']);
            }
        }
        if(!$flow['recruit']){//编制内
           $result[Const_Flow::FLOW_RECRUIT_12] = Const_Flow::FLOW_RECRUIT_12;
           $result[Const_Flow::FLOW_RECRUIT_13] = Const_Flow::FLOW_RECRUIT_13;
        }
        //直接取消的
        $res = $this->_get_cancel_hide($operate_log, $flow);
        //最高上级
        $relations = $this->relations;
        $relation_count = count($relations[$flow['user_id']]);
        //cxo上级
        $cxo_uids = $this->_get_cxo_user_ids();
        $ceo_uid = APF::get_instance()->get_config('ceo_uid');
        foreach($relations[$flow['user_id']] as $parents){
            if($parents!=$ceo_uid && in_array($parents, $cxo_uids) && in_array($ceo_uid, $relations[$flow['user_id']])){
                $relation_count = $relation_count-1;
            }
        }
        $relation_hide = $this->_get_cxo_operate_next_leader($relation_count+1);
        if(!$relation_count){
            $relation_hide = $this->_get_cxo_operate_next_leader(2);
            $relation_hide[Const_Flow::FLOW_RECRUIT_2] = Const_Flow::FLOW_RECRUIT_2;
        }
        $relation_hide = array_keys($relation_hide);
        return array_merge($res,$result,$relation_hide);
    }
    //需要隐藏的流程
    private function _get_cxo_operate_next_leader($stage){
        $opt_list = $this->_build_all_flows();
        $result = array();
        if($stage >= Const_Flow::FLOW_RECRUIT_2 && $stage <= Const_Flow::FLOW_RECRUIT_11){
            for($i=$stage+1;$i <= Const_Flow::FLOW_RECRUIT_11;$i++){
                $result[$i] = $opt_list[$i]['phase'];//这里应该是阶段对应动作
            }
        }
        return $result;
    }
    /**
     * 撤销
     */
    private function _get_cancel_hide($operate_log,$flow){
        $result = array();
        $max_flow = 0;
        if($flow['now_status'] == Const_Flow::FLOW_STATUS_CANCEL ){
            foreach($operate_log as $log){
                if($max_flow<$log['flow_stage']){
                    $max_flow = $log['flow_stage'];
                }
            }
            for($i=$max_flow+1;$i<=Const_Flow::FLOW_RECRUIT_14;$i++){
                $result[]=$i;
            }
        }
        return $result;
    }
    /**
     * post 验证
     */
    private function _check_post_param($allow_opt,$params){
        $boolean = true;
        $data = array();
        foreach($allow_opt as $opt_id){
            $temp = $this->_get_post_data($params, $opt_id);
            $data = array_merge($data,$temp[0]);
        }
        foreach($data as $key => $val){
            if(preg_match('/[a-z]*_apply/', $key)){
                if($val == 2){
                    $reason = explode('_', $key);
                    $reason_key = $reason[0].'_reason';
                    if(!$data[$reason_key] || !trim($data[$reason_key])){
                        $this->error_item[$reason_key]="true";
                        $boolean = false;
                    }
                }elseif($key == "hr_apply" && (!$data['hr_lumesse'] || !trim($data['hr_lumesse'] || empty($this->lums_dep)))){
                    $this->error_item['hr_lumesse']="true";
                    $boolean = false;
                }
            }
        }
        return $boolean;
    }
    /**
     * 获取当前可操作阶段
     * //最多两级编辑权限
     */
    private function _get_flow_stage($operate_log,$flow){

        $role_list = $this->user_info['role_list'];
        $this->_do_flow_stage($role_list,$operate_log,$flow);
        $allow_opt = array();
        foreach($this->flow_stage as $flow_stage){
            $allow_opt[$flow_stage] = max($this->_get_flow_step(Const_Flow::FLOW_TYPE_RECRUIT,$flow_stage));
        }
        //地方hr没有权限编辑编制外的
        //hr招聘分城市权限
        if(isset($role_list[Const_Flow::ROLE_RECRUIT]) || isset($role_list[Const_Flow::ROLE_HRD])){
            $citys = array();
            if(isset($role_list[Const_Flow::ROLE_HRD]) && in_array(Const_Flow::FLOW_RECRUIT_12, $this->flow_stage)){
                $citys = array_merge($citys,$role_list[Const_Flow::ROLE_HRD]);
            }
            if(isset($role_list[Const_Flow::ROLE_RECRUIT]) && in_array(Const_Flow::FLOW_RECRUIT_14, $this->flow_stage)){
                $citys = array_merge($role_list[Const_Flow::ROLE_RECRUIT],$citys);
            }
            if($citys && !in_array($flow['work_city_id'], $citys)){
               $this->flow_stage = array();
               $allow_opt = array();
            }
        }
        return $allow_opt;
    }
    /**
     * 检测主管关系
     * @param unknown_type $flow_id
     * @param unknown_type $flow_stage
     * @return boolean
     */
    private function _check_superior_relation_right($flow_id,$flow_stage){
        $data = array();
        $data['user_id'] = $this->get_user_id();
        $data['flow_stage'] =$flow_stage;
        //$data['is_deleted'] = Const_Util::IS_DELETE_NO;
        $relation = $this->_get_bll_flow_relation()->get_relation($flow_id, $data);
        if($relation){
            return true;
        }
        return false;
    }

    /**
     * 处理flow_stage
     */
    private function _do_flow_stage($role_list,$operate_log,$flow){
        //只有跳过主管到hr的
        if($flow['flow_stage'] == Const_Flow::FLOW_RECRUIT_1 && isset($role_list[Const_Flow::ROLE_SUPERIOR])){//一级办理
            if($this->relations[$flow['user_id']][0]==$this->user_info['user_id']){
                $this->flow_stage[] = Const_Flow::FLOW_RECRUIT_2;
            }
        }elseif( $flow['flow_stage'] >= Const_Flow::FLOW_RECRUIT_2 && $flow['flow_stage'] <= Const_Flow::FLOW_RECRUIT_10 && in_array($this->user_info['user_id'],$this->relations[$flow['user_id']])){//二级办理
            //操作人是申请人的主管关系
            $all_flows = $this->_build_all_flows();
            $now_flow = $all_flows[$flow['flow_stage']];
            if($operate_log[$now_flow['phase']]['opt_user_id'] == $this->get_user_id()){
                $this->flow_stage[$flow['flow_stage']] = $flow['flow_stage'];
            }else{
                $this->flow_stage[$now_flow['next_stage']] = $now_flow['next_stage'];
            }
        }elseif($flow['flow_stage'] == Const_Flow::FLOW_RECRUIT_11){//hrd,cxo,主管
           if($flow['recruit']){//编制外,hrd,cxo,主管
                if(isset($role_list[Const_Flow::ROLE_SUPERIOR]) && $this->view){//主管 编辑
                    $cxo_list = $this->_get_cxo_user_ids();//cxo级和vp有决定权);
                    if(in_array($this->get_user_id(), $cxo_list)){//cxo跳步
                        $flow_stage = $this->_get_min_flow_stage_cxo($operate_log,$role_list);
                        $this->flow_stage[$flow_stage] = $flow_stage;
                    }else{
                        $this->flow_stage[Const_Flow::FLOW_RECRUIT_10] = Const_Flow::FLOW_RECRUIT_10;
                    }
                }
                if($role_list[Const_Flow::ROLE_HRD] && !$this->view){//hrd 办理
                    $this->flow_stage[Const_Flow::FLOW_RECRUIT_12] = Const_Flow::FLOW_RECRUIT_12;
                }
            }
        }elseif($flow['flow_stage'] == Const_Flow::FLOW_RECRUIT_12){//hrd,ceo
            if(isset($role_list[Const_Flow::ROLE_HRD])&& $this->view){
                $this->flow_stage[Const_Flow::FLOW_RECRUIT_12] = Const_Flow::FLOW_RECRUIT_12;
            }
            if(isset($role_list[Const_Flow::ROLE_CEO]) && !$this->view){
                $this->flow_stage[Const_Flow::FLOW_RECRUIT_13] = Const_Flow::FLOW_RECRUIT_13;
            }
        }elseif($flow['flow_stage'] == Const_Flow::FLOW_RECRUIT_13 ){//hr,ceo,主管
            $ceo_superior = false;
            if(isset($role_list[Const_Flow::ROLE_SUPERIOR]) && $this->view){//二级 编辑
                $cxo_list = $this->_get_cxo_user_ids();//cxo级和vp有决定权);
                if(in_array($this->get_user_id(), $cxo_list)){//ceo跳步
                    $recruit = $this->_get_bll_flow_recruit()->get_recruit_by_id($flow['flow_id']);
                    if(!$recruit['hrd_apply']){//hrd没操作过
                        $flow_stage = $this->_get_min_flow_stage_cxo($operate_log,$role_list);
                        $this->flow_stage[$flow_stage] = $flow_stage;
                        $ceo_superior = true;
                    }
                }else{
                    if(!$flow['recruit']){//编制内,hr,ceo,二级
                        $this->flow_stage[Const_Flow::FLOW_RECRUIT_3] = Const_Flow::FLOW_RECRUIT_3;
                    }
                }
            }

            if(isset($role_list[Const_Flow::ROLE_CEO]) && $this->view && $flow['recruit'] && !$ceo_superior){
                $this->flow_stage[Const_Flow::FLOW_RECRUIT_13] = Const_Flow::FLOW_RECRUIT_13;
            }
            if($role_list[Const_Flow::ROLE_RECRUIT] && !$this->view){//hr办理
                $this->flow_stage[Const_Flow::FLOW_RECRUIT_14] = Const_Flow::FLOW_RECRUIT_14;
            }
        }

        //主管编辑权限验证
        foreach($this->flow_stage as $flow_stage){
            if($flow_stage <= Const_Flow::FLOW_RECRUIT_11){
                if(!$this->_check_superior_relation_right($flow['flow_id'],$flow_stage)){
                    unset($this->flow_stage[$flow_stage]);
                }
            }
        }
    }
    /**
     * 获取cxo
     */
    private function _get_cxo_user_ids(){
        if(!$this->cxo_user_ids){
            $this->cxo_user_ids = APF::get_instance()->get_config('role_cxo');
        }
        return $this->cxo_user_ids;
    }
    /**
     * 查找cxo操作
     */
    private function _get_min_flow_stage_cxo($operate_log,$role_list){
        $uids = $this->_get_cxo_user_ids();
        $stage = 100;
        foreach($operate_log as $log){
            if($stage > $log['flow_stage'] && isset($role_list[Const_Flow::ROLE_SUPERIOR]) && in_array($this->get_user_id(), $uids) && $this->get_user_id()==$log['opt_user_id']){
                $stage = $log['flow_stage'];
            }
        }
        return $stage;
    }
    /**
     * 操作日志
     */
    private function _get_operate_log($flow_id){
        $result = array();
        $logs = $this->_get_bll_flow_operate_log()->get_log_by_flow_ids(array($flow_id));
        $opt_user_ids = array();
        foreach($logs as $log){
            $result[$log['flow_opt']]['operate_time'] = date('Y-m-d H:i',strtotime($log['operate_time']));
            $opt_user_ids[] = $log['opt_user_id'];
            $result[$log['flow_opt']]['opt_user_id'] = $log['opt_user_id'];
            $result[$log['flow_opt']]['flow_stage']  = $log['flow_stage'];
        }
        $users = $this->_get_bll_hroa()->get_user_by_ids($opt_user_ids,$get_job=false);
        foreach($result as $key=>$val){
            $result[$key]['opt_user_name'] = $users[$val['opt_user_id']]['name'];
        }
        return $result;
    }
    /**
     * 编制内外处理，cxo（最高主管）处理
     */
    private function _execute_recruit($allow_opt,$param,$flow){
        $new_allow_opt = array();
        $role_list = $this->user_info['role_list'];
        $cxo_list = $this->_get_cxo_user_ids();//cxo级和vp有决定权
        foreach($allow_opt as $key=>$opt_id){
            $new_allow_opt[$key] = $opt_id;
            if($opt_id == Const_Flow::PHASE_51){
               if(in_array($this->user_info['user_id'],$cxo_list)){
                   $flow_stages = $this->_get_cxo_operate_next_leader(Const_Flow::FLOW_RECRUIT_2);
                   foreach($flow_stages as $stage=>$opt){
                       if($opt >=$opt_id){
                           $new_allow_opt[$stage] = $opt;
                       }
                   }
                   if(!$flow['recruit']){//编制内
                       $new_allow_opt[Const_Flow::FLOW_RECRUIT_12] = Const_Flow::PHASE_55;
                       $new_allow_opt[Const_Flow::FLOW_RECRUIT_13] = Const_Flow::PHASE_56;
                   }
                }
            }elseif($opt_id == Const_Flow::PHASE_52){
                if(!$flow['recruit']){//编制内
                   $flow_stages = $this->_get_cxo_operate_next_leader(Const_Flow::FLOW_RECRUIT_3);
                   foreach($flow_stages as $stage=>$opt){
                       if($opt >=$opt_id){
                           $new_allow_opt[$stage] = $opt;
                       }
                   }
                   $new_allow_opt[Const_Flow::FLOW_RECRUIT_12] = Const_Flow::PHASE_55;
                   $new_allow_opt[Const_Flow::FLOW_RECRUIT_13] = Const_Flow::PHASE_56;
                }
                if(in_array($this->user_info['user_id'],$cxo_list)){//CXO
                    $flow_stages = $this->_get_cxo_operate_next_leader(Const_Flow::FLOW_RECRUIT_3);
                    foreach($flow_stages as $stage=>$opt){
                        if($opt >=$opt_id){
                            $new_allow_opt[$stage] = $opt;
                        }
                    }
                }
            }elseif($opt_id == Const_Flow::PHASE_53 || ($opt_id >= Const_Flow::PHASE_70 && $opt_id <= Const_Flow::PHASE_76)){//只有编制外
                if(in_array($this->user_info['user_id'],$cxo_list)){//CXO
                    $flow_stages = $this->_get_cxo_operate_next_leader(Const_Flow::FLOW_RECRUIT_4);
                    foreach($flow_stages as $stage=>$opt){
                        if($opt >=$opt_id){
                            $new_allow_opt[$stage] = $opt;
                        }
                    }
                }
            }
        }
        return $this->_execute_post($new_allow_opt,$param,$flow);
    }
    /**
     * 检测前面是否审批过一次
     */
    private function _first_apply_log($flow,$flow_stage,$opt_id){
        $user_id = $opt_id == Const_Flow::PHASE_55 ? 6872 : 6932;
        $opt_log = $this->_get_bll_flow_operate_log()->find_opt_log($flow['flow_id'], $user_id);
        if(empty($opt_log)){
            return false;
        }
        $data2['apply_last_opt'] = intval(date('Ymd'));
        if($opt_id == Const_Flow::PHASE_55){
            $data2['hrd_apply'] = 1;
        }elseif($opt_id == Const_Flow::PHASE_56){
            $data2['ceo_apply'] = 1;
        }
        $tre = $this->_get_bll_flow_recruit()->update_recruit_by_id($flow['flow_id'],$data2);

        $log_array = array(
                'flow_id'=>$flow['flow_id'],
                'user_id'=>$flow['user_id'],
                'user_name'=>$flow['user_name'],
                'city_id'=>$flow['work_city_id'],
                'apply_user_id'=>1,//TODO如果是跳流程的应该填0,第一个算自己操作的
                'role_type'=>Const_Flow::ROLE_SYSTEM,
                'flow_opt'=>$opt_id,
                'flow_stage'=>$flow_stage+1,
                'effective_date' =>$flow['effect_date']
        );
        $lre = $this->_get_bll_flow_transfer()->add_opt_log($log_array,$flow['flow_id']);
        $flow_data = array(
            'flow_type'=>$flow['flow_type'],
            'flow_stage'=>$flow_stage+1,
            'flow_opt'=>$opt_id,
            'flow_role_list'=>Const_Flow::ROLE_RECRUIT
                );
        $fre = $this->_get_bll_flow()->update_flow_data($flow_data,array('flow_id'=>$flow['flow_id']));
        return true;
    }
    /**
     * 处理办理流程
     */
    private function _execute_post($allow_opt,$param,$flow){
        $role_list = $this->user_info['role_list'];
        //操作成功标记位
        $error_msg = '';
        $i=0;
        $max_opt=0;
        foreach($allow_opt as $flow_stage=>$opt_id){
            $max_opt = $flow_stage;

            //更新flow表用的数据
            $data = array('flow_type'=>$flow['flow_type'],'flow_stage'=>$flow_stage,'flow_opt'=>$opt_id);

            //更新recruit表用的数据
            $temp = $this->_get_post_data($param,$opt_id);
            $data2 = $temp[0];

            $flow_id = $flow['flow_id'];
            //更新基本信息
            $data2['apply_last_opt'] = intval(date('Ymd'));
            $tre = $this->_get_bll_flow_recruit()->update_recruit_by_id($flow_id,$data2);
            if(!$tre){
                $error_msg = '&update_recruit-error';
                break;
            }
            //先记LOG,如果是同步执行的编辑，实际上获取不到role，因此save_log()方法更新LOG时不更新role_type
            $role = $this->_get_flow_step($flow['flow_type'],$flow_stage,$opt_id);
            $user_id = $i==0 ? $this->user_info['user_id'] : 0;
            $log_array = array(
                    'city_id'=>$flow['work_city_id'],
                    'apply_user_id'=>$user_id,//TODO如果是跳流程的应该填0,第一个算自己操作的
                    'role_type'=>$role,
                    'flow_opt'=>$opt_id,
                    'flow_stage'=>$flow_stage,
                    'effective_date' =>$flow['effect_date']
            );
            $i++;
            $lre = $this->_get_bll_flow_transfer()->add_opt_log(array_merge($flow,$data2,$log_array),$flow_id);
            if(!$lre){
                $error_msg = '&update_log-error';
                break;
            }
            #驳回不再往下执行
            if($temp[1]){
                $this->_get_bll_flow_transfer()->clear_parent_relation($flow_id);
                $this->_do_cancel($flow_id);
                break;
            }
            //更新relation表
            $rre = true;
            if(($opt_id >= Const_Flow::PHASE_51 && $opt_id <= Const_Flow::PHASE_53) || ($opt_id >= Const_Flow::PHASE_70 && $opt_id <= Const_Flow::PHASE_76)){
                if(empty($param['view'])){
                    $rre = $this->_get_bll_flow_transfer()->clear_parent_relation($flow_id);
                }
                if(($opt_id == Const_Flow::PHASE_51 && !$flow['recruit']) || ($opt_id < Const_Flow::PHASE_76 && $flow['recruit'])){
                    $cxo_list = $this->_get_cxo_user_ids();//cxo级和vp有决定权
                    if($rre && !in_array($this->get_user_id(), $cxo_list) && empty($param['view'])){//TODO
                        $rre = $this->_get_bll_flow_transfer()->add_parent_relation($this->get_user_id(), $flow_id,$flow_stage+1,false);
                    }
                }
            }
            if(!$rre){
                $error_msg = '&update_relation-error';
                break;
            }
            //只有办理时才更新flow表
            $fre = $this->_get_bll_flow()->update_flow($flow_id,array_merge($data,$data2));
            if(!$fre || in_array($fre,array(1,2))){
                $error_msg = '&update_flow-error';
                break;
            }
            if($fre == 4){//流程结束
                $this->_get_bll_flow_recruit()->update_recruit_by_id($flow_id, array('apply_status'=>Const_Flow::FLOW_STATUS_EFFECT));

                //同步到lumesse
                $this->_execute_hr_lumesse($flow_id);
            }
        }

        //检测到了11阶段,
        //如果下一级是HRD和ceo阶段,如果前面审批过的,直接跳转后面的,这里是多了处理，所以不退出
        if($max_opt+1==Const_Flow::FLOW_RECRUIT_12){
            $ks = $this->_first_apply_log($flow,$max_opt,Const_Flow::PHASE_55);
        }elseif($max_opt+1==Const_Flow::FLOW_RECRUIT_13){
            $kt = $this->_first_apply_log($flow,$max_opt,Const_Flow::PHASE_56);
        }
        return  $error_msg;
    }
    /**
     * 同步错误处理
     */
    private function execute_input_error($flow){
        $role_list = $this->user_info['role_list'];
        $recruit = $this->_get_bll_flow_recruit()->get_recruit_by_id($flow['flow_id']);
        $nex_url = Flow_Urls::flow_list();
        if(!isset($role_list[Const_Flow::ROLE_RECRUIT])){
            $this->show_tips('ERROR_AUTH',$nex_url,Const_Tip::ERROR);
        }
        if($flow['now_status']!=Const_Flow::FLOW_STATUS_EFFECT){
            $this->show_tips('ERROR_LUMS_NO_END',$nex_url,Const_Tip::ERROR);
        }
        if($recruit['lums_position_id']){
            $this->show_tips('ERROR_LUMS_SYNC_EVER',$nex_url,Const_Tip::ERROR);
        }
        $this->_execute_hr_lumesse($flow['flow_id']);
        if($recruit['hr_lumesse']){
            $this->show_tips('OPT_SUCCESS',$nex_url,1);
        }else{
            $this->show_tips('ERROR_PARAM',$nex_url,Const_Tip::ERROR);
        }

    }
    /**
     * 流程结束
     * 同步招聘信息到招聘系统
     */
     private function _execute_hr_lumesse($flow_id){
         //防止修改提交
         $recruit = $this->_get_bll_flow_recruit()->get_recruit_by_id($flow_id);
         if($recruit['hr_lumesse']){//create
             $lumesse_user_all = Bll_Flow_Lumesse::get_instance()->get_user_by_id($recruit['user_id']);
             if(!empty($lumesse_user_all)){
                 if(count($lumesse_user_all)==1){//TODO后面再整理
                     //$lumesse_user = $lumesse_user_all[0];
                     $lumesse_user['user_id'] = $recruit['user_id'];
                     $lumesse_user['lums_depart_id'] = $recruit['lums_dep_id'];
                     $lumesse_user['lums_depart_ename'] = $this->lums_dep[$recruit['lums_dep_id']]['lums_depart_ename'];
                 }else{
                 //重新区取如果lums_depart_id=0的,说明这个员工处理顶级,需要从数据库获取信息,部门英文//有账号才能同步
                     if($_GET['sync_lums_dep_id'] && $_GET['sync']){
                         $recruit['lums_dep_id'] = $_GET['sync_lums_dep_id'];
                         $this->_get_bll_flow_recruit()->update_recruit_by_id($flow_id,array('lums_dep_id'=>$_GET['sync_lums_dep_id']));
                     }
                     $lumesse_user['user_id'] = $recruit['user_id'];
                     $lumesse_user['lums_depart_id'] = $recruit['lums_dep_id'];
                     $lumesse_user['lums_depart_ename'] = $this->lums_dep[$recruit['lums_dep_id']]['lums_depart_ename'];
                 }
                 //更新最后操作人
                 $this->_get_bll_flow_recruit()->update_recruit_by_id($flow_id,array('opt_user_id'=>$this->user_info['user_id']));
                 $data = $this->_build_lumesse_position_data($recruit,$lumesse_user);
                 $lumesse_hris_position = Bll_Flow_Lumesse::get_instance()->Lumesse_HRIS()->Position();
                 $res = $lumesse_hris_position->createPosition(array("position"=>$data));
                 if(!$res || !$res->position || !$res->position->id){
                     $this->show_tips('ERROR_LUMS_SYNC_ERROR',"/flow/",Const_Tip::ERROR);
                 }
                 $this->_get_bll_flow_recruit()->update_recruit_by_id($flow_id, array('lums_position_id'=>$res->position->id));
             }
         }
     }

    /**
     * 构建招聘所需数据
     */
    private function _build_lumesse_position_data($recruit,$lumesse_user){
        apf_require_class('Const_User');
        $position_types = Const_User::get_hroa_to_lumesse_user_type();

        $data = array();
        $data['contractType'] = $position_types[$recruit['user_type']];//员工类型
        $data['headCount'] = $recruit['job_needs'];//招聘人数
        $data['status'] = 'Open';//开启状态
        $data['plainText'] = false;
        $data['title'] = $recruit['hr_lumesse'];//职位名称
        if(!empty($this->user_info['office_mail'])){
            $res = array(//招聘小组
                    0=>array(
                            'email'=>$this->user_info['office_mail'],
                    )
            );
            $data['team'] = array('recruiter'=>$res);
        }

        $organization_unit = array(
                    'id'=>$lumesse_user['lums_depart_id'],
                    'code'=>$lumesse_user['lums_depart_ename'],
                    'level'=>1
                );
        /*
        $organization_unit[] = array(
                'id'=>$lumesse_user['lums_pdepart_id'],
                'code'=>$lumesse_user['lums_pdepart_ename'],
                'level'=>1
        );
        if($lumesse_user['lums_depart_ename']){
            $organization_unit[] = array(
                    'id'=>$lumesse_user['lums_depart_id'],
                    'code'=>$lumesse_user['lums_depart_ename'],
                    'level'=>2
            );
        }*/
        $data['organization'] = array('unit'=>$organization_unit);//所属部门

        $freeFormField = array();
        $address = Const_Flow::office_address();
        $address = $address[$recruit['work_city_id']][$recruit['work_address']];
        $freeFormField[] = array(//工作地点
                                        '_'=>$address,
                                        'keygroup'=>'Position Info',
                                        'keyfield'=>'Work Location',
        );
        if($recruit['is_written']==1 && $recruit['written_info']){
            $freeFormField[] = array(//笔试题目
                                        '_'=>$recruit['written_info'],
                                        'keygroup'=>'test info',
                                        'keyfield'=>'test name',
            );
        }

        $leader_job_name="";
        $user_info = $this->_get_bll_hroa()->get_user_by_ids(array($lumesse_user['user_id']));
        $leader_job_name = $user_info[$lumesse_user['user_id']]['job_name'];
        $freeFormField[] = array(//汇报上级
                                        '_'=>$leader_job_name,
                                        'keygroup'=>'Position Info',
                                        'keyfield'=>'Report To',
        );
        $data['configurableFields'] = array('freeFormFields'=>array('freeFormField'=>$freeFormField));
       /*  $work_core_list = Const_Flow::work_core();
        $work_core_ids = explode(',', $recruit['work_core']);
        $work_core = array();
        foreach($work_core_ids as $w_id){
            $work_core[] = $work_core_list[$w_id];
        } */
        $data['customField'] = array(
                array(//工作职责 = 工作职责+岗位要求
                        'label'=>'Field1',
                        'order'=>1,
                        'value'=>nl2br($recruit['work_plus']),
                ),
                array(//应聘条件 = 核心能力+专业能力
                        'label'=>'Field2',
                        'order'=>2,
                        'value'=>nl2br($recruit['work_skilled']),
                ),
        );
        return $data;
    }
    /**
     * 驳回不再继续执行
     * @param unknown_type $flow_id
     * @param unknown_type $data2
     */
    private function _do_cancel($flow_id){
        $this->_get_bll_flow_recruit()->update_recruit_by_id($flow_id, array('apply_status'=>Const_Flow::FLOW_STATUS_CANCEL));
        $this->_get_bll_flow()->update_flow_cancel($flow_id);
    }
    /**
     * 获取提交数据
     */
    private function _get_post_data($param,$opt_id){
        $boolean = false;
        $data2 = array();
        $allow_temp = $this->_get_submit_names($opt_id);
        foreach($allow_temp as $row){
            if(preg_match('/[a-z]*_apply/', $row)){
                $apply = intval($param[$row]);
                $data2[$row] = $apply;
                if($apply == 2){//驳回
                    $boolean = true;
                }
            }else{
                $data2[$row] = htmlspecialchars($param[$row]);
            }
        }
        /* foreach($data2 as $key => $val){
            if(preg_match('/[a-z]*_apply/', $key)){
                $reason = explode('_', $key);
                $reason_key = $reason[0].'_reason';
                if($val == 1){
                    $data2[$reason_key] = "";
                }
            }
        } */
        return array($data2,$boolean);
    }
    /**
     * 获得该操作允许的页面input的name
     */
    private function _get_submit_names($opt_id){
        $return = array();
        if(!$opt_id){
            return $return;
        }
        $name_list = array(
                Const_Flow::PHASE_51=>array('first_apply','first_reason'),
                Const_Flow::PHASE_52=>array('second_apply','second_reason'),
                Const_Flow::PHASE_53=>array('third_apply','third_reason'),
                Const_Flow::PHASE_54=>array('hr_apply','hr_reason','hr_lumesse','lums_dep_id'),
                Const_Flow::PHASE_55=>array('hrd_apply','hrd_reason'),
                Const_Flow::PHASE_56=>array('ceo_apply','ceo_reason'),
                Const_Flow::PHASE_70=>array('four_apply','four_reason'),
                Const_Flow::PHASE_71=>array('five_apply','five_reason'),
                Const_Flow::PHASE_72=>array('six_apply','six_reason'),
                Const_Flow::PHASE_73=>array('seven_apply','seven_reason'),
                Const_Flow::PHASE_74=>array('eight_apply','eight_reason'),
                Const_Flow::PHASE_75=>array('nine_apply','nine_reason'),
                Const_Flow::PHASE_76=>array('ten_apply','ten_reason'),
        );
        if(isset($name_list[$opt_id])){
            $return = $name_list[$opt_id];
        }

        return $return;
    }
    /**
     * 构建其它所需信息
     */
    private function _build_recruit_info($recruit){
        //部门 职位
        $bus = $this->_get_bll_hroa()->get_business_list();
        $job_info = $this->_get_bll_hroa()->get_job_dep_info($recruit['job_id']);
        $recruit['department_name'] = $job_info['department_name'];
        $recruit['position_name'] = $job_info['position_name'];
        $recruit['bu_name'] = $bus[$job_info['bu_id']]['bu_name'];
        $recruit['old_plan_num'] = $job_info['job_plan_num'];
        $recruit['old_fact_num'] = $job_info['job_fact_num'];
        //职工类型
        $types = $this->_get_bll_hroa()->get_all_user_type();
        $recruit['type_name'] = $types[$recruit['user_type']]['type_name'];
        //职级
        if($recruit['is_p_m'] == Const_User::RECRUIT_USER_TYPE_M){
            $m_degrees = $this->_get_bll_hroa()->get_m_degree();
            $recruit['p_m_start'] = $m_degrees[$recruit['m_start']]['degree'];
            $recruit['p_m_end'] = $m_degrees[$recruit['m_end']]['degree'];
        }elseif($recruit['is_p_m'] == Const_User::RECRUIT_USER_TYPE_P){
            $p_degrees = $this->_get_bll_hroa()->get_p_degree();
            $recruit['p_m_start'] = $p_degrees[$recruit['p_start']]['degree'];
            $recruit['p_m_end'] = $p_degrees[$recruit['p_end']]['degree'];
        }
        //工作地址
        $address = Const_Flow::office_address();
        $recruit['address_name'] = $address[$recruit['work_city_id']][$recruit['work_address']];
        //能力要求
        if($recruit['work_core']){
            $work_cores = Const_Flow::work_core();
            $temp = explode(',', $recruit['work_core']);
            $temp_work_core = array();
            foreach($temp as $val){
                $temp_work_core[] = $work_cores[$val];
            }
            $recruit['work_core'] = implode('，', $temp_work_core);
        }
        $recruit['created'] = date('Y-m-d',$recruit['created']);
        return $recruit;
    }
    /**
     * 待办事项
     * @return Bll_Flow_Info
     */
    private function _get_bll_flow(){
        if(!$this->bll_flow ){
            apf_require_class('Bll_Flow_Info');
            $this->bll_flow = new Bll_Flow_Info();
        }
        return $this->bll_flow;
    }
    /**
     * 招聘记录
     * @return Bll_Flow_Recruit
     */
    private function _get_bll_flow_recruit(){
        if(!$this->bll_flow_recruit ){
            apf_require_class('Bll_Flow_Recruit');
            $this->bll_flow_recruit = new Bll_Flow_Recruit();
        }
        return $this->bll_flow_recruit;
    }
    /**
     * @return Bll_Hr_OutInterface
     */
    private function _get_bll_hroa(){
        if(!$this->bll_hroa ){
            apf_require_class('Bll_Hr_OutInterface');
            $this->bll_hroa = new Bll_Hr_OutInterface();
        }
        return $this->bll_hroa;
    }
    /**
     * @return Bll_Flow_Transfer
     */
    private function _get_bll_flow_transfer(){
        if(!$this->bll_flow_transfer ){
            apf_require_class('Bll_Flow_Transfer');
            $this->bll_flow_transfer = new Bll_Flow_Transfer();
        }
        return $this->bll_flow_transfer;
    }
    /**
     * @return Bll_Flow_OperateLog
     */
    private function _get_bll_flow_operate_log(){
        if(!$this->bll_flow_operate_log ){
            apf_require_class('Bll_Flow_OperateLog');
            $this->bll_flow_operate_log = new Bll_Flow_OperateLog();
        }
        return $this->bll_flow_operate_log;
    }
    /**
     * @return Bll_Flow_ApplyRelation
     */
    private function _get_bll_flow_relation(){
        if(!$this->bll_flow_relation ){
            apf_require_class('Bll_Flow_ApplyRelation');
            $this->bll_flow_relation = new Bll_Flow_ApplyRelation();
        }
        return $this->bll_flow_relation;
    }
}